import re
import time
from flask import request
from flask_restful import abort
from flask_login import current_user, login_user
from funcy import project
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import IntegrityError
from funcy import partial

from redash import models, limiter
from redash.permissions import (
    require_admin,
)
from redash.handlers.base import (
    BaseResource,
    require_fields,
    get_object_or_404,
    paginate,
    order_results as _order_results,
)

from redash.authentication.account import (
    invite_link_for_user,
    send_invite_email,
    send_password_reset_email,
    send_verify_email,
)
from redash.settings import parse_boolean
from redash import settings



class Workflow_transitionNewResource(BaseResource):
    @require_admin
    def post(self):
        req = request.get_json(force=True)
        require_fields(req, ("workflowid","workflow_stateid"))

        workflow_transition = models.Workflow_transition(
            userid=req["userid"],
            org=self.current_org,
            workflowid=req["workflowid"],
            workflow_stateid=req["workflow_stateid"],
            next_type=req["next_type"],
            next_workflow_stateid=req["next_workflow_stateid"],
            allow_user=req["allow_user"],
            allow_group=req["allow_group"],
            allow_col=req["allow_col"],
            condition=req["condition"],
        )
        try:
            models.db.session.add(workflow_transition)
            models.db.session.commit()
        except IntegrityError as e:
            if "name" in str(e):
                abort(400, message="编号已存在.")
            abort(500)

        # timeserial.record_event(
        #     {"action": "create", "object_id": timeserial.id, "object_type": "timeserial"}
        # )

class Workflow_transitionResource(BaseResource):
    def get(self, workflow_transition_id):
        result = models.Workflow_transition.get_by_id(workflow_transition_id)
        return result.to_dict()

    @require_admin
    def post(self, workflow_transition_id):
        req = request.get_json(force=True)
        require_fields(req, ("workflowid","workflow_stateid"))

        workflow_transition = models.Workflow_transition.get_by_id(workflow_transition_id)
        params = dict(workflowid=req["workflowid"],workflow_stateid=req["workflow_stateid"],
            next_type=req["next_type"],next_workflow_stateid=req["next_workflow_stateid"],
            allow_user=req["allow_user"],allow_group=req["allow_group"],
            allow_col=req["allow_col"],condition=req["condition"],)
        try:
            self.update_model(workflow_transition, params)
            models.db.session.commit()
        except IntegrityError as e:
            if "name" in str(e):
                abort(400, message="名称已存在.")
            abort(500)

class Workflow_transitiondeleteResource(BaseResource):
    @require_admin
    def post(self, workflow_transition_id):
        workflow_transition =  models.Workflow_transition.get_by_id(workflow_transition_id)
        models.db.session.delete(workflow_transition)
        models.db.session.commit()

class Workflow_transitionListResource(BaseResource):
    def post(self):
        req = request.get_json(force=True)
        page = req["page"]
        page_size = req["pagesize"]
        name = req["name"]
        workflowid = str(req["workflowid"])
        strwhere ="t1.org_id=" +str(self.current_org.id)
        if name !='' :
            strwhere = strwhere + " and t1.name like '%"+name+"%'"
        if workflowid !='' :
            strwhere = strwhere + " and t1.workflowid = "+workflowid+""
        strgetfield ="""  t1.*,t2.name statename, t3.name nextstatename, case when next_type=1 then '通过' else '驳回' end actionname,
          array(SELECT name FROM users WHERE id = ANY(t1.allow_user)) username,
          array(SELECT name FROM groups WHERE id = ANY(t1.allow_group)) groupname """

        tblname = """ workflow_transition t1 left join workflow_state t2 on t1.workflow_stateid = t2.id
                left join workflow_state t3 on t1.next_workflow_stateid = t3.id  """
        orderfield ="t1.id"
        result = models.Enums.get_pagequery(tblname,strgetfield,orderfield,page_size,page,0,strwhere)
        return result[0]
